<?php
declare (strict_types = 1);

namespace app\admin\controller;

use think\facade\Event;
use think\Request;
use app\BaseController;
use app\model\User as UserModel;
class User extends BaseController
{
    /**
     * 登录
     *
     * @return \think\Response
     */
    protected $_user = '';
    public function login(Request $request)
    {
        $data = $request->post();
        $this->validate($data, [
            'username' => 'require',
            'password' => 'require',
        ],[
            'username.require' => '账号不能为空',
            'password.require' => '密码不能为空',
        ]);
        $user = UserModel::where('username',$data['username'])->field('password,id')->find();
        if(empty($user)){
            return $this->error('用户名或密码错误');
        }
        if (password_verify($data['password'], $user->password) === false) {
            return $this->error('用户名或密码错误');
        }
        if (password_needs_rehash($user->password, PASSWORD_DEFAULT, ['cost'=>10])) {
            $user->password = password_hash($data['password'], PASSWORD_DEFAULT, ['cost' => 10]);
        }
        $token = Event::trigger('AdminLogin', $user, true);
        return $this->success("登录成功!", $token);
    }

    public function read()
    {
//        $data = Event::until($token);
        $data=array();
        $info=array();
        $data['roles']=["admin"];
        $data['phone']="13168776766";
        $data['username']="admin";
        $data['introduction']="管理员";
        $data['name']="Super Admin";
        $data['userId']="1122222";
        $info['user']=$data;
        return $this->success("登录成功!", $info);
    }

    public function logout()
    {
        return $this->success("退出成功!");
    }

}
